package com.wgke.bluetooth.ui;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.util.Log;
import android.view.View;

import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;

import com.newmobiler.android.ui.adapter.CellAdapter;
import com.newmobiler.android.ui.adapter.OnItemClickListener;
import com.newmobiler.android.ui.adapter.cell.DataBinder;
import com.newmobiler.android.ui.adapter.cell.MultiCell;
import com.newmobiler.android.ui.adapter.viewholder.RVViewHolder;
import com.wgke.bluetooth.R;
import com.wgke.bluetooth.event.EventBean;
import com.wgke.bluetooth.event.EventGattBean;
import com.wgke.bluetooth.tools.GattServiceBean;
import com.wgke.bluetooth.ui.dialog.BaseDialog;
import com.wgke.bluetooth.ui.dialog.ChooseDialog;
import com.wgke.bluetooth.utils.BluetoothGattManager;
import com.wgke.bluetooth.utils.SpUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.ConnectVM;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class BluetoothConnectActivity extends BaseListActivity<ConnectVM> {

    BluetoothDevice device;

    @Override
    public int layoutId() {
        return R.layout.activity_connect;
    }

    @Override
    public int itemId() {
        return R.layout.item_service;
    }

    @Override
    public void initOtherView() {
        device = BluetoothGattManager.getInstance().getDevice();
        if (device == null) {
            vm.isFinishPage.postValue(true);
            return;
        }
        requestPermissions2(0);
        vm.list.observe(this, this::setAdapter);
        findViewById(R.id.tvAnyong).setOnClickListener(v -> {
            if (!SpUtil.getUseParse()) {
                ToastUtil.showLongMsg("请在首页菜单>解析策略>启用尝试解析");
            } else if (!SpUtil.getUsePolicy()) {
                ToastUtil.showLongMsg("请在首页菜单>解析策略>启用解析策略");
            } else if (BluetoothGattManager.getInstance().getServices() == null) {
                ToastUtil.showMsg("服务被清理，请刷新");
            } else {
                List<GattServiceBean> list = vm.list.getValue();
                for (GattServiceBean bean : list) {
                    if (bean.uuid.toString().startsWith("0000fa00")) {
                        Intent intent = new Intent(this, ReadWrite2Activity.class);
                        intent.putExtra("uuid", bean.uuid.toString());
                        intent.putExtra("title", BluetoothGattManager.getInstance().getServiceName(bean.uuid));
                        startActivity(intent);
                        return;
                    }
                }
            }
        });
    }

    public void setAdapter(List<GattServiceBean> list) {
        Log.e("BluetoothConnectActivity", "setAdapter: " + list.size());
        BluetoothGattManager bgm = BluetoothGattManager.getInstance();
        setAdapter(list, (vh, c) -> {
            vh.setText(R.id.tvTitle, bgm.getServiceName(c.uuid));
            vh.setText(R.id.tvContent, "uuid:" + c.uuid.toString());
            CellAdapter adapter = CellAdapter.createAdapter(vh.getView(R.id.rv));
            adapter.setDataList(MultiCell.convert2(R.layout.item_character, c.list, (h, b) -> {
                h.setText(R.id.tvCTitle, bgm.getCharacteristicName(b.uuid));
                h.setText(R.id.tvCContent, "uuid:" + b.uuid.toString());
                String type = BluetoothGattManager.getPropertyDescription(b.properties);
                h.setText(R.id.tvCType, type);
                h.setVisibility(R.id.ivSignWrite, type.contains("WRITE") ? View.VISIBLE : View.GONE);
                h.setVisibility(R.id.ivSignRead, type.contains("READ") ? View.VISIBLE : View.GONE);
            }));
            adapter.setOnItemClickListener((var1, var2) -> {
                if (bgm.getServices() == null) {
                    ToastUtil.showMsg("服务被清理，请刷新");
                    return;
                }
                chooseActivity(c);
            });
        });
    }

    public void chooseActivity(GattServiceBean c) {
        ChooseDialog chooseDialog = new ChooseDialog(this, new int[]{0, 1}, new String[]{"默认", "十二气囊床垫"}, "选择入口");
        chooseDialog.setCallback((index, value) -> {
            Intent intent = new Intent(BluetoothConnectActivity.this, ReadWriteActivity.class);
            if (index == 1) {
                intent = new Intent(BluetoothConnectActivity.this, RWActivity.class);
            }
            intent.putExtra("uuid", c.uuid.toString());
            intent.putExtra("title", BluetoothGattManager.getInstance().getServiceName(c.uuid));
            startActivity(intent);
        });
        chooseDialog.show();

    }

    @Override
    protected void initStateBar() {
        super.initStateBar();
        // 使用获取到的 BluetoothDevice 对象
        @SuppressLint("MissingPermission") String deviceName = device.getName();
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(deviceName);
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    @Override
    public void nextStep(int i) {
        if (i <= 1) return;
        vm.scanService();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        if (event.status == 2) {
            ToastUtil.showMsg("蓝牙已断开");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventGattBean event) {
        if (event.status == 1) {
            ToastUtil.showMsg("已经获取到数据");
            vm.scanService();
        } else {
            ToastUtil.showMsg("获取服务失败");
        }
    }

    @Override
    public void onRefresh() {
        postDelayed(1000, this::finishRefresh);
    }

    @Override
    public void finish() {
        super.finish();
        BluetoothGattManager.getInstance().close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothGattManager.getInstance().close();
    }
}
